import {Component, OnInit, ViewChild} from '@angular/core';
import {BaseGridComponent, BaseService} from '@sb/base';
import {SysParamService} from '../service/sys-param.service';
import {STColumn} from '@delon/abc';
import {SFSchema, SFSelectWidgetSchema, SFTextareaWidgetSchema} from '@delon/form';
import {NzMessageService} from 'ng-zorro-antd';
import {SysParam} from '../entity/sys-param';
import {SysAttachmentUploadAlainComponent} from '../../sys-attachment/sys-attachment-upload/sys-attachment-upload-alain.component';
import {SysAttachmentUploadSchema} from '../../sys-attachment/sys-attachment-upload/sys-attachment-upload-schema';
import {SysParamTreeNode} from '../entity/sys-param-tree-node';
import {SysParamTreeSelectPanelComponent} from '../sys-param-tree-select-panel/sys-param-tree-select-panel.component';
import {
    SysCodeCategorySelectAlainComponent,
    SysCodeCategorySelectAlainSchema
} from '../../sys-code/sys-code-category-select-alain/sys-code-category-select-alain.component';
import {
    SysCodeTreeSelectAlainComponent,
    SysCodeTreeSelectAlainSchema
} from '../../sys-code/sys-code-tree-select-alain/sys-code-tree-select-alain.component';
import {SFItemComponent} from '@delon/form/src/sf-item.component';
import {SFComponent} from '@delon/form/src/sf.component';
import {NzTreeNode} from 'ng-zorro-antd/core/tree/nz-tree-base-node';

@Component({
    selector: 'sys-param',
    templateUrl: './sys-param.component.html',
    styleUrls: ['./sys-param.component.less'],
    providers: [
        {
            provide: BaseService,
            useClass: SysParamService
        }
    ]
})
export class SysParamComponent implements OnInit {

    columns: STColumn[] = [
        {
            title: '',
            type: 'checkbox',
            index: 'paramId',
            width: '5%',
            className: 'text-center word-wrap'
        }, {
            title: '参数名',
            index: 'paramName',
            width: '50%',
            format: (item: SysParam, col, index) => {
                let v = item.paramName;
                if (item.remark) {
                    v += '（' + item.remark + '）';
                }
                return v;
            },
            className: 'word-wrap'
        }, {
            title: '类型',
            index: 'valueType',
            width: 60,
            className: 'text-center word-wrap',
            format: (item, col, index) => {
                switch (item.valueType) {
                    case 'DIR':
                        return '目录';
                    case 'TEXT':
                        return '文本';
                    case 'NUMBER':
                        return '数值';
                    case 'BOOLEAN':
                        return '布尔值';
                    case 'SYS_CODE':
                        return '数据字典';
                    case 'ATTACHMENT':
                        return '附件';
                    default:
                        return '';
                }
            }
        }, {
            title: '参数值',
            index: 'paramValue',
            width: '15%',
            className: 'text-center word-wrap'
        }, {
            title: '操作区',
            width: 120,
            className: 'text-center word-wrap',
            buttons: []
        }
    ];

    schema: SFSchema = {
        properties: {
            paramName: {
                type: 'string',
                title: '参数名',
                // minLength: 2
            },
            valueType: {
                type: 'string',
                title: '类型',
                enum: [
                    {label: '目录', value: 'DIR'},
                    {label: '文本', value: 'TEXT'},
                    {label: '数值', value: 'NUMBER'},
                    {label: '布尔值', value: 'BOOLEAN'},
                    {label: '数据字典', value: 'SYS_CODE'},
                    {label: '附件', value: 'ATTACHMENT'},
                ],
                ui: {
                    widget: 'select',
                } as SFSelectWidgetSchema,
            },
            paramValueText: {
                type: 'string',
                title: '参数值',
                ui: {
                    widget: 'textarea',
                    autosize: {minRows: 4, maxRows: 8},
                    visibleIf: {
                        valueType: ['TEXT']
                    },
                } as SFTextareaWidgetSchema,
            },
            paramValueNumber: {
                type: 'number',
                title: '参数值',
                // minimum: 18, maximum: 100,
                ui: {
                    visibleIf: {
                        valueType: ['NUMBER']
                    },
                }
            },
            paramValueBoolean: {
                type: 'boolean',
                title: '参数值',
                ui: {
                    visibleIf: {
                        valueType: ['BOOLEAN']
                    },
                }
            },
            paramValueAttachment: {
                type: 'string',
                title: '附件',
                ui: {
                    widget: SysAttachmentUploadAlainComponent.KEY,
                    multiple: false,
                    visibleIf: {
                        valueType: ['ATTACHMENT']
                    },
                    baseAttachmentService: this.sysParamService,
                    baseAttachmentParam: {
                        paramName: 'paramName'
                    }
                } as SysAttachmentUploadSchema,
            },
            sysCodeModule: {
                type: 'string',
                title: '字典模块',
                ui: {
                    widget: SysCodeCategorySelectAlainComponent.KEY,
                    multiple: false,
                    visibleIf: {
                        valueType: ['SYS_CODE']
                    },
                    valueChange: (value: string, sfItemComp: SFItemComponent, sfComp: SFComponent) => {
                        const prop = sfComp.getProperty('/paramValueSysCode');
                        const widget: SysCodeTreeSelectAlainComponent = prop.widget as SysCodeTreeSelectAlainComponent;
                        widget.updateCategory(value);
                    }
                } as SysCodeCategorySelectAlainSchema,
            },
            paramValueSysCode: {
                type: 'string',
                title: '字典项',
                ui: {
                    widget: SysCodeTreeSelectAlainComponent.KEY,
                    multiple: false,
                    visibleIf: {
                        valueType: ['SYS_CODE']
                    },
                } as SysCodeTreeSelectAlainSchema,
            },
            remark: {
                type: 'string',
                title: '描述',
                ui: {
                    widget: 'textarea',
                    autosize: {minRows: 2, maxRows: 4},
                } as SFTextareaWidgetSchema,
            }
        },
        required: ['paramName', 'valueType'],
        ui: {
            spanLabelFixed: 100,
            grid: {
                span: 23
            }
        }
    };

    selectedNode: SysParamTreeNode;
    selectedNzTreeNode: NzTreeNode;

    baseParam: SysParam = {
        parentId: '-1'
    };


    @ViewChild('baseGrid', {static: false})
    baseGrid: BaseGridComponent;

    @ViewChild('sysParmaTree', {static: false})
    sysParmaTree: SysParamTreeSelectPanelComponent;

    constructor(
        private sysParamService: SysParamService,
        private message: NzMessageService) {
    }

    commitWrapper(value: SysParam) {
        if (value.valueType === 'TEXT') {
            value.paramValue = value.paramValueText;
            delete value.paramValueText;
        } else if (value.valueType === 'NUMBER') {
            value.paramValue = value.paramValueNumber;
            delete value.paramValueNumber;
        } else if (value.valueType === 'ATTACHMENT') {
            value.paramValue = value.paramValueAttachment;
            delete value.paramValueAttachment;
        } else if (value.valueType === 'BOOLEAN') {
            value.paramValue = value.paramValueBoolean;
            delete value.paramValueBoolean;
        } else if (value.valueType === 'SYS_CODE') {
            value.paramValue = value.paramValueSysCode;
            if (value.sysCodeModule) {
                value.options = JSON.stringify({
                    module: value.sysCodeModule
                });
            }
            delete value.paramValueAttachment;
        }
        return value;
    }

    recordWrapper(value: SysParam) {
        if (value.valueType === 'TEXT') {
            value.paramValueText = value.paramValue;
        } else if (value.valueType === 'NUMBER') {
            value.paramValueNumber = value.paramValue;
        } else if (value.valueType === 'ATTACHMENT') {
            value.paramValueAttachment = value.paramValue;
            const ui = this.schema.properties.paramValueSysCode.ui as SysAttachmentUploadSchema;
            ui.baseAttachmentParam = {
                paramName: value.paramName
            };
            // todo 此处暂时不需要，因后台暂时未做校验
            // if (this.baseGrid && this.baseGrid.baseDetail) {
            //     this.baseGrid.baseDetail.sf.refreshSchema(this.schema);
            // }
        } else if (value.valueType === 'BOOLEAN') {
            value.paramValueBoolean = value.paramValue;
        } else if (value.valueType === 'SYS_CODE') {
            value.paramValueSysCode = value.paramValue;
            const options = JSON.parse(value.options);
            value.sysCodeModule = options.module;

            if (options.module) {
                const ui = this.schema.properties.paramValueSysCode.ui as SysCodeTreeSelectAlainSchema;
                ui.category = options.module;
                if (this.baseGrid && this.baseGrid.baseDetail) {
                    this.baseGrid.baseDetail.sf.refreshSchema(this.schema);
                }
            }
        }
        delete value.paramValue;
        return value;
    }

    // onSelectNode(treeNode: SysParamTreeNode) {
    onSelectNode(nzTreeNode: NzTreeNode) {
        this.selectedNzTreeNode = nzTreeNode;
        this.selectedNode = nzTreeNode.origin as SysParamTreeNode;
        this.baseParam.parentId = nzTreeNode && nzTreeNode.key || '-1';

        if (this.baseGrid) {
            this.baseGrid.reload();
        }
    }

    onDataReload() {
        this.sysParmaTree.reloadNode(this.baseParam.parentId || '-1');
    }

    ngOnInit(): void {

    }

    detailClose($event: boolean) {
        const node = this.sysParmaTree.baseTree.nzTree.getTreeNodeByKey(this.baseParam.parentId || '-1');
        this.sysParmaTree.reloadNode(node.parentNode.key);
    }
}
